import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//server tcp

@SuppressWarnings("all")
public class TCPServer {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);

        // 创建服务端
        ServerSocket server = new ServerSocket(8888);
        // 监听连接 返回socket对象
        Socket socket = server.accept();
        String ip = socket.getInetAddress().toString().substring(1);
        System.out.println( "Form IP:" + ip + " client is connecting...\n");

        InputStream inputStream = null;
        OutputStream outputStream = null;

        while(true){
            // 获取client socket 里面的信息
            inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String output = bufferedReader.readLine();
            if("exit".equals(output)){
                System.out.println( "Form IP:" + ip + " client has exited.\n");
                break;
            }
            System.out.println(output);

            // 向client发送信息
            outputStream = socket.getOutputStream();
            System.out.print("server> ");
            String input = scanner.nextLine();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(input);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }



        System.out.println("\nserver has exited.");


        outputStream.close();
        inputStream.close();
        socket.close();
        server.close();
    }
}
